<template>
  <view class="address-edit-page">
    <!-- 表单容器 -->
    <view class="form-container">
      <u--form
          :model="formData"
          :rules="rules"
          ref="addressForm"
          labelWidth="180"
      >
        <!-- 收货人 -->
        <u-form-item prop="takePeople" required>
          <template slot="label">
            <text class="required-label">
              <text class="required-star">*</text>
              收货人
            </text>
          </template>
          <u--input
              v-model="formData.takePeople"
              placeholder="请输入收货人姓名"
              placeholderStyle="color:#C9CDD4;font-size:28rpx"
              border="none"
              maxlength="20"
              clearable
          ></u--input>
        </u-form-item>

        <!-- 联系电话 -->
        <u-form-item prop="mobile" required>
          <template slot="label">
            <text class="required-label">
              <text class="required-star">*</text>
              联系电话
            </text>
          </template>
          <u--input
              v-model="formData.mobile"
              placeholder="请输入11位手机号码"
              placeholderStyle="color:#C9CDD4;font-size:28rpx"
              border="none"
              type="number"
              maxlength="11"
              clearable
          ></u--input>
        </u-form-item>

        <!-- 收货地址 -->
        <u-form-item prop="address" required>
          <template slot="label">
            <text class="required-label">
              <text class="required-star">*</text>
              收货地址
            </text>
          </template>
          <u-input maxlength="30" placeholderStyle="background:#f7f8fa;color:#C9CDD4"
                   :custom-style="{padding:'10rpx 20rpx',lineHeight:'74rpx',fontSize:'28rpx',backgroundColor:'#F7F8FA',height:'74rpx'}"
                   v-model="formData.address" border="none" placeholder="请填写收货地址">
            <template slot="suffix">
              <u-button type="primary" text="选择位置" @click="getLocation"></u-button>
            </template>
          </u-input>
        </u-form-item>

        <!-- 设为默认地址 -->
        <u-form-item label="设为默认" borderBottom>
          <u-switch
              v-model="isDefaultAddr"
              :activeValue="true"
              :inactiveValue="false"
              size="45"
          ></u-switch>
        </u-form-item>
      </u--form>
      <!-- 底部按钮 -->
      <view class="bottom-action">
        <u-button
            type="primary"
            :loading="loading"
            @click="submitForm"
            class="submit-btn"
        >
          {{ isNew ? '保存地址' : '更新地址' }}
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import baseConfig from "@/config/baseUrl";

const chooseLocation = requirePlugin('chooseLocation');

export default {
  data() {
    return {
      isNew: true, // 判断是新增还是编辑
      addressInfo: {}, // 原始地址信息
      loading: false, // 提交loading状态
      // 表单数据
      formData: {
        takePeople: '', // 收货人
        mobile: '', // 联系电话
        address: '', // 收货地址
        coord: '', // 地址坐标
        userId: '', // 用户ID
        status: 0 // 默认地址 0-否，1-是
      },
      // 表单验证规则
      rules: {
        takePeople: [
          {
            required: true,
            message: '请输入收货人姓名',
            trigger: ['blur', 'change']
          },
          {
            min: 2,
            max: 20,
            message: '收货人姓名长度在2到20个字符',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            required: true,
            message: '请选择收货地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  computed: {
    // 用于双向绑定默认地址开关
    isDefaultAddr: {
      get() {
        return this.formData.status === 1
      },
      set(value) {
        this.formData.status = value ? 1 : 0
      }
    },
    // 获取用户信息
    userInfo() {
      return this.$store.getters.userInfo || {}
    }
  },
  onLoad(option) {
    this.isNew = option.mode === 'add'

    // 设置用户ID
    this.formData.userId = this.userInfo.id || ''

    if (!this.isNew && option.id) {
      this._getAddrinfo(option.id)
    }

    console.log('地址编辑页面参数:', option)
  },
  onShow() {
    //地图插件选点
    const location = chooseLocation.getLocation();
    if (location != null) {
      // console.log('获取地址信息', location);
      this.formData.address = location.address
      this.formData.coord = JSON.stringify(location) //发送给后台字符串
    }
  },
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },
  methods: {
    // 获取地址信息方便回显
    async _getAddrinfo(id) {
      try {
        const params = {id}
        const res = await this.$api.getMssdUserAddrById(params)

        if (res.success && res.result) {
          this.addressInfo = res.result

          // 回显表单数据
          this.formData = {
            takePeople: res.result.takePeople || '',
            mobile: res.result.mobile || '',
            address: res.result.address || '',
            coord: res.result.coord || '',
            userId: res.result.userId || this.userInfo.id || '',
            status: res.result.status || 0
          }
        } else {
          uni.showToast({
            title: '获取地址信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取地址信息失败:', error)
        uni.showToast({
          title: '获取地址信息失败',
          icon: 'none'
        })
      }
    },

    // 地图选点
    getLocation() {
      const key = baseConfig.mapData.mapKey; //使用在腾讯位置服务申请的key
      const referer = baseConfig.mapData.appName //调用插件的app的名称
      let location = ''
      if (this.formData.coord) {
        let tLocation = JSON.parse(this.formData.coord)
        location = JSON.stringify({
          latitude: tLocation.latitude,
          longitude: tLocation.longitude
        });
      }

      this.getPermission('scope.userLocation', () => {
        uni.navigateTo({
          url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`
        });
      })
    },
    getPermission(scope, callback) {
      // 读取 小程序已经授权的权限
      uni.getSetting({
        success(res) {
          console.log(res);
          // 判断是否拥有此权限进行拉起授权  和 重新授权功能
          if (!res.authSetting[scope]) {
            uni.authorize({
              scope: scope,
              success() {
                callback()
              },
              fail(err) {
                uni.showModal({
                  title: '检测到您已拒绝位置授权，是否重新授权',
                  success(res) {
                    if (res.confirm) {
                      uni.openSetting({
                        success() {
                          console.log('开启权限成功');
                        },
                        fail() {
                          console.log('开启权限失败');
                        }
                      });
                    } else if (res.cancel) {
                      console.log('拒绝开启开启权限');
                    }
                  }
                });
              }
            })
          } else {
            callback()
          }
        }
      })
    },

    // 提交表单
    async submitForm() {
      try {
        // 表单验证
        await this.$refs.addressForm.validate()

        if (!this.formData.coord) {
          uni.showToast({
            title: '请选择收货地址',
            icon: 'none'
          })
          return
        }

        this.loading = true

        // 构造提交数据
        const submitData = {
          ...this.formData,
          userId: this.userInfo.id || this.formData.userId
        }

        // 编辑模式需要传递ID
        if (!this.isNew && this.addressInfo.id) {
          submitData.id = this.addressInfo.id
        }

        console.log('提交的地址数据:', submitData)

        // 调用API
        let res
        if (this.isNew) {
          res = await this.$api.addMssdUserAddr(submitData)
        } else {
          res = await this.$api.editMssdUserAddr(submitData)
        }

        if (res.success) {
          uni.showToast({
            title: this.isNew ? '地址添加成功' : '地址更新成功',
            icon: 'none'
          })

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res.message || '操作失败')
        }

      } catch (error) {
        console.error('提交失败:', error)

        if (error.message) {
          uni.showToast({
            title: error.message,
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.address-edit-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8fafe 0%, #f2f6fc 100%);
  display: flex;
  flex-direction: column;
}

/* 表单容器 */
.form-container {
  flex: 1;
  background-color: #fff;
  margin: 16rpx 16rpx 0;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.08),
  0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

/* 底部操作按钮 */
.bottom-action {
  padding: 24rpx 16rpx;
  padding-bottom: 24rpx;
  background: linear-gradient(180deg, rgba(248, 250, 254, 0) 0%, rgba(248, 250, 254, 0.8) 40%, #f8fafe 100%);

  /deep/.submit-btn {
    width: 100%;
    height: 110rpx;
    border-radius: 48rpx;
    font-size: 32rpx;
    font-weight: 600;
    background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
    box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.3);
    transition: all 0.3s ease;
  }

  .submit-btn:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.4);
  }
}

/* uView表单组件样式优化 */
/deep/ .u-form-item {
  padding: 0rpx 32rpx !important;
  border-bottom: 1rpx solid #f0f2f5 !important;
}

/deep/ .u-form-item__body {
  min-height: 80rpx !important;
  align-items: center !important;
}

/deep/ .u-form-item__body__left__text {
  font-size: 30rpx !important;
  color: #2c3e50 !important;
  font-weight: 500 !important;
  margin-right: 24rpx !important;
}

/deep/ .u-form-item__body__right {
  flex: 1 !important;
}

/deep/ .u-form-item__body__right__content__slot {
  flex: 1 !important;
  width: 100% !important;
}

/* 输入框样式 */
/deep/ .u-input {
  background: #f8f9fa !important;
  border-radius: 12rpx !important;
}

/deep/ .u-input__content {
  padding: 0 20rpx !important;
  min-height: 74rpx !important;
  background: #fff !important;
}

/deep/ .u-input__content__field-wrapper__field {
  font-size: 28rpx !important;
  color: #2c3e50 !important;
  line-height: 1.4 !important;
}

/* 占位符样式通过placeholderStyle属性设置 */

/* 选择位置按钮样式 */
/deep/ .u-button--primary {
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%) !important;
  border: none !important;
  border-radius: 20rpx !important;
  font-size: 24rpx !important;
  font-weight: 600 !important;
  padding: 0 20rpx !important;
  height: 60rpx !important;
  line-height: 60rpx !important;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3) !important;
  transition: all 0.2s ease !important;
}

/deep/ .u-button--primary:active {
  transform: translateY(1rpx) !important;
  box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.4) !important;
}

/deep/ .u-button__text {
  color: #fff !important;
}

/* 开关组件样式 */
/deep/ .u-switch {
  transform: scale(1.1) !important;
}

/deep/ .u-switch__bg {
  border: 2rpx solid #e4e7ed !important;
  transition: all 0.3s ease !important;
}

/deep/ .u-switch--on {
  background: #4a90e2 !important;
  border-color: #4a90e2 !important;
}

/deep/ .u-switch__node {
  background: #fff !important;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15) !important;
}

/* 表单项特殊样式（移除 first/last-child 以兼容 WXSS） */

/* 必填标签样式 */
.required-label {
  font-size: 30rpx;
  color: #2c3e50;
  font-weight: 500;
}

.required-star {
  color: #ff4757;
  margin-right: 4rpx;
  font-weight: bold;
}

/* 收货地址特殊处理 */
/deep/ .u-form-item__body__right__content__slot {
  display: flex !important;
  align-items: center !important;
  gap: 16rpx !important;
}

/* 移除响应式 @media 以兼容 WXSS */

/* 优化表单区域间距 */
/deep/ .u-form {
  background: transparent !important;
}

/* 输入框焦点状态 */
/deep/ .u-input--focus {
  background: #fff !important;
  box-shadow: 0 0 0 2rpx rgba(74, 144, 226, 0.2) !important;
}

/* 页面滚动优化 */
.address-edit-page {
  padding-bottom: 160rpx;
}

/* 微调表单项高度 */
/deep/ .u-form-item__body {
  min-height: 88rpx !important;
}

/* 地址输入框readonly状态 */
/deep/ .u-input--disabled {
  opacity: 1 !important;
}

/deep/ .u-input--disabled .u-input__content__field-wrapper__field {
  color: #606266 !important;
}
</style>
